package com.zhejiangzhengyuan.municipal_way.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhejiangzhengyuan.municipal_common.entity.*;
import com.zhejiangzhengyuan.municipal_common.entity.dto.DeleteFileDto;
import com.zhejiangzhengyuan.municipal_common.entity.dto.FileDto;
import com.zhejiangzhengyuan.municipal_common.entity.vo.BridgeVo;
import com.zhejiangzhengyuan.municipal_common.mapper.*;
import com.zhejiangzhengyuan.municipal_common.response.ResponseVo;
import com.zhejiangzhengyuan.municipal_common.service.BIService;
import com.zhejiangzhengyuan.municipal_common.service.BridgeGisService;
import com.zhejiangzhengyuan.municipal_common.service.InspectionTasksService;
import com.zhejiangzhengyuan.municipal_common.utils.ConstantUtil;
import com.zhejiangzhengyuan.municipal_common.utils.excelFileUtils.ExcelResolveListener;
import com.zhejiangzhengyuan.municipal_common.utils.excelFileUtils.ExcelUtil;
import com.zhejiangzhengyuan.municipal_common.utils.excelFileUtils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/** @author lin_ju Create on 2019/11/28 */
@RestController
@Slf4j
@RequestMapping("/way/bridge")
@Api(tags = "桥梁相关信息")
public class BridgeGisController {
  @Autowired private BridgeGisService bridgeGisService;
  @Autowired private BridgeGisMapper bridgeGisMapper;
  @Autowired private FileMapper fileMapper;
  @Autowired private BridgeFileMappingMapper bridgeFileMappingMapper;
  @Autowired private RoadFileMappingMapper roadFileMappingMapper;
  @Autowired private BIService biService;

  @Autowired
  private SubsidiaryFacilitiesGisFileMappingMapper subsidiaryFacilitiesGisFileMappingMapper;

  @Autowired private InspectionTasksService inspectionTasksService;

  //  @ApiOperation("根据ID查询图片地址")
  //  @GetMapping("/selectLinkByBridgeId")
  //  public ResponseVo selectLinkByBridgeId(Long id){
  //    List<String> linkList = fileMapper.selectByBid(id);
  //    return linkList==null?
  //            ResponseVo.SERVER_ERROR:
  //            new ResponseVo<>(ConstantUtil.ResultCode.SUCCESS, linkList);
  //  }

  @ApiOperation("更新桥梁文件")
  @PostMapping("/updateBridgeFile")
  public ResponseVo updateBridgeFile(@ModelAttribute FileDto dto) {
    return bridgeGisService.updateBridgeFile(dto) > 0
        ? ResponseVo.SUCCESS
        : ResponseVo.CLIENT_PARAM_ERROR;
  }

  @ApiOperation("查询桥梁信息并分页")
  @GetMapping("/selectAllBridge")
  public ResponseVo selectAllBridge(@ApiParam("页码") Long page, @ApiParam("每页显示条数") Long limit) {
    page = Objects.isNull(page) || page <= 0 ? 1 : page;
    limit = Objects.isNull(limit) || limit <= 0 ? 14 : limit;
    Page<BridgeVo> bridgeVoPage = new Page<>(page, limit);
    IPage<BridgeVo> bridgeVoIPage = bridgeGisService.selectAllBridge(bridgeVoPage);
    return Objects.isNull(bridgeVoIPage)
        ? ResponseVo.SERVER_ERROR
        : new ResponseVo<>(ConstantUtil.ResultCode.SUCCESS, bridgeVoIPage);
  }

  @ApiOperation("导入桥梁")
  @RequestMapping(value = "/importBridgeGis", method = RequestMethod.POST)
  public ResponseVo importRoad(@RequestParam("file") MultipartFile file) {
    return ExcelUtil.readExcel(file, BridgeGis.class, new ExcelResolveListener<>(bridgeGisService));
  }

  @ApiOperation("桥梁模糊查询")
  @RequestMapping(value = "/FuzzyBridge", method = RequestMethod.GET)
  public ResponseVo FuzzyBridge(
      String bridgeName, String code, @ApiParam("页码") Long page, @ApiParam("每页显示条数") Long limit) {
    page = Objects.isNull(page) || page <= 0 ? 1 : page;
    limit = Objects.isNull(limit) || limit <= 0 ? 14 : limit;
    Page<BridgeVo> bridgeVoPage = new Page<>(page, limit);
    Page<BridgeVo> bridgeGis = bridgeGisMapper.FuzzyBridge(bridgeVoPage, bridgeName, code);
    List<BridgeVo> records = bridgeGis.getRecords();
    for (BridgeVo bridgeVo : records) {
      List<String> strings = fileMapper.selectByBid(bridgeVo.getId());
      if (strings == null || strings.size() == 0) {
        bridgeVo.setLink(strings);
      }
    }
    return ResponseVo.successWithData(bridgeGis);
  }

  @ApiOperation("删除文件")
  @PostMapping("/deleteWay")
  public ResponseVo deleteWay(@ModelAttribute DeleteFileDto dto) {
    if (dto.getLinkList() == null || dto.getType() == null) {
      return ResponseVo.CLIENT_PARAM_ERROR;
    }
    // 删除文件
    String link = dto.getLinkList();
    String[] linkList = FileUtil.getUrlsByRequest(link);
    String type = dto.getType();
    if (linkList == null || linkList.length == 0) {
      return ResponseVo.SUCCESS;
    }
    switch (type) {
      case "桥梁":
        for (String s : linkList) {
          QueryWrapper<File> fileQueryWrapper = new QueryWrapper<>();
          fileQueryWrapper.eq("link", s);
          File file = fileMapper.selectOne(fileQueryWrapper);
          if (file != null) {
            QueryWrapper<BridgeFileMapping> bridgeFileMappingQueryWrapper = new QueryWrapper<>();
            bridgeFileMappingQueryWrapper.eq("file_id", file.getId());
            if (bridgeFileMappingMapper.delete(bridgeFileMappingQueryWrapper) > 0) {
              fileMapper.deleteById(file.getId());
              try {
                FileUtil.removeFile(s);
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
        }
        return ResponseVo.SUCCESS;
      case "道路":
        for (String s : linkList) {
          QueryWrapper<File> fileQueryWrapper = new QueryWrapper<>();
          fileQueryWrapper.eq("link", s);
          File file = fileMapper.selectOne(fileQueryWrapper);
          if (file != null) {
            QueryWrapper<RoadFileMapping> roadFileMappingQueryWrapper = new QueryWrapper<>();
            roadFileMappingQueryWrapper.eq("file_id", file.getId());
            if (roadFileMappingMapper.delete(roadFileMappingQueryWrapper) > 0) {
              fileMapper.deleteById(file.getId());
              try {
                FileUtil.removeFile(s);
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
        }
        return ResponseVo.SUCCESS;
      case "附属设施":
        for (String s : linkList) {
          QueryWrapper<File> fileQueryWrapper = new QueryWrapper<>();
          fileQueryWrapper.eq("link", s);
          File file = fileMapper.selectOne(fileQueryWrapper);
          if (file != null) {
            QueryWrapper<SubsidiaryFacilitiesGisFileMapping>
                subsidiaryFacilitiesGisFileMappingQueryWrapper = new QueryWrapper<>();
            subsidiaryFacilitiesGisFileMappingQueryWrapper.eq("file_id", file.getId());
            if (subsidiaryFacilitiesGisFileMappingMapper.delete(
                    subsidiaryFacilitiesGisFileMappingQueryWrapper)
                > 0) {
              fileMapper.deleteById(file.getId());
              try {
                FileUtil.removeFile(s);
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
        }
        return ResponseVo.SUCCESS;
    }

    return ResponseVo.CLIENT_PARAM_ERROR;
  }

  @ApiOperation("手机端桥梁专题，数据显示")
  @GetMapping(value = "/mobileTerminalBridgeDisplay")
  public ResponseVo mobileTerminalRoadDisplay(Integer month) {
    String type = "桥梁";
    return ResponseVo.successWithData(biService.getBICount(type, month, null));
  }

  @ApiOperation("手机端舞阳桥洞专题和振兴桥洞，数据显示")
  @GetMapping(value = "/mobileTerminalDisplay1")
  public ResponseVo mobileTerminalBridgeHoleDisplay(Integer month) {
    String deviceName = "舞阳桥洞水尺";
    JSONObject result = new JSONObject();
    result.put("舞阳桥洞", biService.getBridgeHole(deviceName, month));
    deviceName = "振兴桥洞水尺";
    result.put("振兴桥洞", biService.getBridgeHole(deviceName, month));
    return ResponseVo.successWithData(result);
  }

  @ApiOperation("手机端304立交桥洞和春晖桥洞专题，数据显示")
  @GetMapping(value = "/mobileTerminalDisplay2")
  public ResponseVo mobileTerminalLiJiaBridgeHoleDisplay(Integer month) {
    String deviceName = "304桥洞水尺";
    JSONObject result = new JSONObject();
    result.put("304桥洞", biService.getBridgeHole(deviceName, month));
    deviceName = "春晖桥洞水尺";
    result.put("春晖桥洞", biService.getBridgeHole(deviceName, month));
    return ResponseVo.successWithData(result);
  }

  @ApiOperation("设置当前页和每页显示条数")
  @GetMapping("/findPage")
  public ResponseVo findPage(@ApiParam("页码") Long page, @ApiParam("每页显示条数") Long limit) {
    // pageNo默认为1；size默认为14
    page = page == null || page <= 0 ? 1 : page;
    limit = limit == null || limit <= 0 ? 14 : limit;
    IPage<BridgeGis> bridgeGisIPage = bridgeGisService.page(page, limit);
    return bridgeGisIPage == null
        ? new ResponseVo<>(ConstantUtil.ResultCode.SERVER_ERROR, "没有数据")
        : new ResponseVo<>(ConstantUtil.ResultCode.SUCCESS, bridgeGisIPage);
  }

  @ApiOperation("根据ID删除")
  @DeleteMapping("/removeBridgeById/{id}")
  public ResponseVo removeBridgeById(@PathVariable Integer id) {
    return bridgeGisService.removeById(id) ? ResponseVo.SUCCESS : ResponseVo.SERVER_ERROR;
  }

  @ApiOperation("根据ID 批量删除 格式：'ids':[7,9,10]")
  @DeleteMapping("/removeBridgeByIds")
  public ResponseVo removeBridgeByIds(@RequestBody Map<String, List<Integer>> map) {
    List<Integer> idList = map.get("ids");
    return bridgeGisService.removeByIds(idList) ? ResponseVo.SUCCESS : ResponseVo.SERVER_ERROR;
  }

  @ApiOperation("根据ID更新")
  @PutMapping("/updateBridge")
  public ResponseVo updateBridge(@RequestBody @Validated BridgeGis bridgeGis) {

    return bridgeGisService.updateBridge(bridgeGis) > 0
        ? ResponseVo.SUCCESS
        : ResponseVo.SERVER_ERROR;
  }

  @ApiOperation("添加桥梁")
  @PostMapping("/insertBridge")
  public ResponseVo saveBridge(
      @ApiParam(name = "添加桥梁字段", required = true) @ModelAttribute BridgeGis bridgeGis) {
    return bridgeGisService.saveBridge(bridgeGis) > 0
        ? new ResponseVo<>(ConstantUtil.ResultCode.SUCCESS, bridgeGis)
        : ResponseVo.SERVER_ERROR;
  }

  @ApiOperation("根据坐标查询桥梁 ")
  @GetMapping("/findPointByBridge")
  public ResponseVo findPointByBridge(String startPoint, String endPoint) {
    BridgeGis bridgeGis = bridgeGisService.findPointByBridge(startPoint, endPoint);
    return Objects.isNull(bridgeGis)
        ? ResponseVo.CLIENT_PARAM_ERROR
        : new ResponseVo<>(ConstantUtil.ResultCode.SUCCESS, bridgeGis);
  }

  @ApiOperation("导出数据")
  @GetMapping("/export")
  public void excelRoad(HttpServletResponse response) {
    QueryWrapper<BridgeGis> wrapper = new QueryWrapper<>();
    QueryWrapper<BridgeGis> id = wrapper.orderByAsc("id");
    List<BridgeGis> list = bridgeGisService.list(id);
    HashSet<String> exclude = new HashSet<>();
    exclude.add("createTime");
    exclude.add("updateTime");
    ExcelUtil.objectToExcelAndDownload(response, exclude, "桥梁数据表", BridgeGis.class, list);
  }
}
